import React from 'react';
import { View, Text, Image } from "@tarojs/components";
import { observer } from "mobx-react";
import { Wallet_Store_Key } from "@/models/wallet";
import { norInject, INorInjectProps } from "@/models";
import i18n from 'i18n-js';
import moment from 'moment';
import {
  GStyleSheet,
  DynamicColors,
} from '@/utils/DarkMode';
import PageContainer from "@/components/PageContainer";
import { formattingNumByLength } from '@/utils';
import ListItem from '@/components/ListItem';
import { GButton } from '@/components/GButton';
import Toast from '@/utils/Toast';
import gizCoinIcon from '@/assets/images/my_recharg_icon_gizwits_beans.png';

const dstyles = GStyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    flex: 1,
    flexDirection: 'column',
    backgroundColor: DynamicColors.screenBackgroundGaryColor,
  },
  listBox: {
    paddingLeft: 15,
    paddingRight: 15,
    backgroundColor: DynamicColors.cardBackgroundColor,
    // borderBottomColor: '#eee',
    borderBottomWidth: 0,
  },
  listItem: {
    paddingTop: 15,
    paddingBottom: 15,
    paddingLeft: 0,
    paddingRight: 0,
    borderBottomWidth: 0,
  },
  listContent: {
    fontSize: 14,
    color: DynamicColors.normalTextColor,
  },
  listContentTips: {
    fontSize: 14,
    color: DynamicColors.subTitleTextColor,
  },
  titleBox: {
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    display: 'flex',
    height: 120,
  },
  feeBox: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  moneyTitle: {
    fontSize: 30,
    fontWeight: '300',
    color: DynamicColors.normalTextColor,
  },
  moneyTitleTips: {
    fontSize: 14,
    color: DynamicColors.subTitleTextColor,
    marginTop: 10,
  },
});


const detailList = [
  {
    title: 'CHARGE_TYPE',
    dataIndex: 'payType',
  },
  {
    title: 'PAY_MONEY',
    dataIndex: 'payMoney',
  },
  {
    title: 'CREATE_TIME',
    dataIndex: 'ctime',
  },
  {
    title: 'PAY_TIME',
    dataIndex: 'payTime',
  },
  {
    title: 'ORDER_NO',
    dataIndex: 'orderNo',
  },
  {
    title: 'SERIAL_NUM',
    dataIndex: 'tradeNo',
  }
];

interface IProps extends INorInjectProps {

}

@norInject(Wallet_Store_Key)
@observer
export default class ChargeRecordDetail extends React.Component<IProps> {

  state = {
    time: 0,
  }

  componentWillMount() {
    const { wallet: { chargeDetail: { ctime } } } = this.props;
    if (ctime) {
      const restTime = 1800 - (moment().unix() - moment(ctime).unix());
      if (restTime < 0) {
        return;
      }
      this.setState({
        time: restTime,
      });
      this.timer = setInterval(() => {
        const { time } = this.state;
        if (time - 1 <= 0) {
          this.clearTimer();
          this.getDetail();
        }
        this.setState({
          time: time - 1,
        });
      }, 1000);
    }
  }

  componentWillUnmount() {
    this.clearTimer();
    Toast.hideLoading();
  }

  getDetail = async () => {
    console.log('getDetail');
    const { wallet, wallet: { chargeDetail: { orderNo } } } = this.props;
    await wallet.setChargeDetail(orderNo);
  }

  clearTimer = () => {
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  getTime = (time) => {
    if (!time) return '';
    const t = time;
    const h = formattingNumByLength(parseInt(t / 3600, 10), 2);
    const m = formattingNumByLength(parseInt((t % 3600) / 60, 10), 2);
    const s = formattingNumByLength(t % 60, 2);
    return `${h}:${m}:${s}`;
  }

  goPay = async ({ orderNo, payType, chargeModeAdditionalData }) => {
    Toast.loading(i18n.t('BUYING'));
    const { wallet } = this.props;
    const payRes = await wallet.pay({ orderNo, payType, productId: chargeModeAdditionalData });
    Toast.hideLoading();
    let isSuccess = false;
    if (payRes && payRes.isSuccess) {
      isSuccess = true;
    }
    if (isSuccess) {
      wallet.setChargeDetail(orderNo);
      wallet.getBalance();
    }
  }

  cancel = async (orderNo) => {
    const { wallet } = this.props;
    wallet.cancelChargeOrder(orderNo);
  }

  render() {
    const styles = dstyles.style;
    const { time } = this.state;
    const { wallet, wallet: { chargeDetail,
      chargeDetail: { orderNo, status: orderStatus, fee, payType, chargeModeAdditionalData }
    } } = this.props;
    const payTypeList = wallet.supportPayTypeList();
    let status = orderStatus;

    // 支付状态
    let statusText = '';
    switch (status) {
      case 1:
        statusText = 'WAIT_FOR_PAY';
        break;
      case 2:
        statusText = 'PAYING';
        break;
      case 3:
        statusText = 'PAY_FAILED';
        break;
      case 4:
        statusText = 'HAS_PAID';
        break;
      case -1:
        statusText = 'HAS_CANCEL';
        break;
      default:
        break;
    }

    const supportPay = payTypeList.findIndex(i => i === payType) > -1;

    const timeText = this.getTime(time);
    return (
      <PageContainer
        style={styles.container}
        title={i18n.t('CHARGE_DETAIL')}
      >
        <View style={styles.listBox}>
          <View style={styles.titleBox}>
            <View style={styles.feeBox}>
              <Image src={gizCoinIcon} style={{ width: 30, height: 30, marginRight: 5 }} />
              <Text style={styles.moneyTitle}>
                +
                {fee}
              </Text>
            </View>
            <View>
              <Text style={styles.moneyTitleTips}>
                {i18n.t(statusText)}
                {status === 2 && timeText && ` ${timeText}`}
              </Text>
            </View>
          </View>
          {
            detailList.map((item) => {
              const { title, dataIndex } = item;
              let content = chargeDetail[dataIndex];
              if (dataIndex === 'payType') {
                let payType = 'WECHAT';
                if (content === 3) {
                  payType = 'ALIPAY';
                } else if (content === 10) {
                  payType = 'IOS_IN_PURCHASE';
                }
                content = `${i18n.t(payType)}${i18n.t('PAY')}`;
              } else if (dataIndex === 'payMoney') {
                content = `¥${content}`;
              }
              return content && (
                <ListItem
                  style={styles.listItem}
                  extra={(
                    <Text style={styles.listContentTips}>
                      {content}
                    </Text>
                  )}
                >
                  <Text style={styles.listContent}>
                    {i18n.t(title)}
                  </Text>
                </ListItem>
              );
            })
          }
        </View>
        {status === 2 && [
          <GButton
            style={{ marginBottom: 15, marginTop: 30 }}
            text={i18n.t('CANCEL_PAY')}
            onPress={() => { this.cancel(orderNo); }}
            fontSize={14}
            primary
          />,
          supportPay ? (
            <GButton
              style={styles.chargeBtn}
              text={i18n.t('GO_PAY')}
              onPress={() => { this.goPay({ orderNo, payType, chargeModeAdditionalData }); }}
              fontSize={14}
            />
          ) : null
        ]}
      </PageContainer>
    );
  }
}
